<template>
    <div class="com-container">
        <div ref="chartDom" class="com-chart"></div>
    </div>
</template>

<script lang="ts">
import { Vue, Component, Watch, Prop } from 'vue-property-decorator';
import * as echarts from 'echarts';
import Dict from '../dict';
import DictionConstUtil from '@/utils/diction-const-util';

@Component({
    name: 'TaskBarChart',
})
export default class TaskBarChart extends Vue {
    @Prop() data;
    chartInstance: any = null;

    userList: any[] = [];

    @Watch('data', { immediate: true, deep: true })
    onWatchData(newData) {
        if (newData) {
            let that = this;
            this.$nextTick(() => {
                that.updateChart(newData);
            });
        }
    }

    // 柱状图背景色
    get barColor() {
        const value = this.data.type;
        let color;
        switch (value) {
            case 'already-statistics':
                color = '#3c7786';
                break;
            case 'transfinite-track':
                color = '#f59e2c';
                break;
            case 'stastics-pending':
                color = ['#b2dfb9', '#feb580', '#3c7786'];
                break;
            default:
                color = '#ee8f9b';
                break;
        }
        return color;
    }

    mounted() {
        this.initChart();
    }

    initChart() {
        this.chartInstance = echarts.init(this.$refs.chartDom);
        const initOption = {
            color: this.barColor,
            grid: {
                top: '10%',
                bottom: '30px',
                right: '6%',
                left: '8%',
            },
            xAxis: {
                type: 'category',
                data: this.data.xData,
                triggerEvent: true,
                // 设置文本过长超出隐藏...表示
                axisLabel: {
                    interval: 0,
                    formatter: function(params) {
                        let val = '';
                        if (params.length > 5) {
                            val = params.substr(0, 5) + '...';
                            return val;
                        } else {
                            return params;
                        }
                    },
                },
                axisTick: {
                    show: false,
                },
                axisLine: {
                    show: false,
                    lineStyle: {
                        color: '#9999b3',
                    },
                },
            },
            yAxis: {
                type: 'value',
                show: false,
                axisTick: {
                    show: false,
                },
                axisLine: {
                    lineStyle: {
                        color: '#9999b3',
                    },
                },
                splitLine: {
                    show: false,
                },
            },
            series: [
                {
                    type: 'bar',
                    data: this.data.data,
                    label: {
                        show: true,
                        color: '#333',
                        position: 'top',
                        fontWeight: 700,
                        formatter: $event => {
                            return $event.value;
                        },
                    },
                    barMinHeight: 10,
                    barWidth: 45, // 柱图宽度
                    barMaxWidth: 45,
                },
            ],
        };
        this.chartInstance.setOption(initOption);
        this.extension(this.chartInstance);
        // 点击事件
        this.chartInstance.on('click', param => {
            console.log(param, 'param');
            const type = this.data.type;
            if (type == 'already-statistics') {
                // 已办任务统计
                const xTitle = param.name || param.value;
                const arr = DictionConstUtil.PojoToList(Dict.taskTypeOptions);
                const key = arr.find(item => item.dictKeyName === xTitle + '维护')?.dictKey;
                const params = {
                    taskType: key,
                    statusList: ['2', '3'],
                };
                this.$emit('click-bar', { params });
            } else {
                // 待办任务统计 
                const title = this.data.title;
                const arr = DictionConstUtil.PojoToList(Dict.taskTypeOptions);
                const key = arr.find(item => item.dictKeyName == title)?.dictKey;
                const name = param.name || param.value;
                let fundOptStatusList = [DictionConstUtil.ReversePojo(Dict.fundOptStatusPojo)[name]];

                const params = {
                    taskType: String(key),
                    fundOptStatusList,
                    searchType: type,
                    statusList: ['1'],
                };
                console.log(params, '-----------------');
                this.$emit('click-bar', { params });
            }
        });
    }

    updateChart(e) {
        // console.log(e, 'e');
        const dataOption = {
            grid: {
                left: (() => {
                    const data = e.data;
                    if (data.length < 1) {
                        return '30px';
                    }
                    const value = String(Math.max(...data)).length * 13;
                    console.log(e.data, value, 'grid-left');
                    return value > 30 ? value + 'px' : '30px';
                })(),
            },
            series: [
                {
                    data: (() => {
                        // 按合同生效日期待办查询
                        let data = JSON.parse(JSON.stringify(e.data));
                        if (e.type == '2') {
                            const value = data[0];
                            data[0] = {
                                value: value,
                                itemStyle: {
                                    color: '#d9001b',
                                },
                            };
                        }
                        if (e.type == 'stastics-pending') {
                            data = data.map((ele, index) => {
                                return {
                                    value: ele,
                                    itemStyle: {
                                        color: this.barColor[index],
                                    },
                                };
                            });
                        }
                        return data.map((ele, index) => {
                            if (ele.value > 0) {
                                return ele;
                            } else {
                                return ele > 0 ? ele : null;
                            }
                        });
                    })(),
                },
            ],
            xAxis: { data: e.xData },
        };
        this.chartInstance.setOption(dataOption);
        this.extension(this.chartInstance);
    }

    // 鼠标悬浮显示全部内容
    extension(chart) {
        // 注意这里，是以X轴显示内容过长为例，如果是x轴的话，需要把params.componentType == 'xAxis'改为yAxis
        // 判断是否创建过div框,如果创建过就不再创建了
        // 该div用来盛放文本显示内容的，方便对其悬浮位置进行处理
        let elementDiv: any = document.getElementById('extension');
        // elementDiv.disabled = false;
        if (!elementDiv) {
            let div: any = document.createElement('div');

            div.setAttribute('id', 'extension');
            div.style.display = 'block';
            document.querySelector('html').appendChild(div);
        }
        // else {
        //     elementDiv.disabled = true;
        // }

        chart.on('mouseover', function(params) {
            // console.log(params, 'params');

            if (params.componentType == 'xAxis') {
                let elementDiv: any = document.querySelector('#extension') as HTMLElement;
                if (params.value && params.value.length <= 5) {
                    return;
                }
                // elementDiv.disabled = true;
                // 设置悬浮文本的位置以及样式
                let elementStyle =
                    'position: absolute;z-index: 99999;color: #fff;font-size: 12px;padding: 5px;display: inline;border-radius: 4px;background-color: #303133;box-shadow: rgba(0, 0, 0, 0.3) 2px 2px 8px';
                elementDiv.style.cssText = elementStyle;
                elementDiv.innerHTML = params.value;
                document.querySelector('html').onmousemove = function(event) {
                    let elementDiv = document.querySelector('#extension') as HTMLElement;
                    let xx = event.pageX - 10;
                    let yy = event.pageY + 15;
                    elementDiv.style.top = yy + 'px';
                    elementDiv.style.left = xx + 'px';
                };
            }
        });
        chart.on('mouseout', function(params) {
            if (params.componentType == 'xAxis') {
                let elementDiv = document.querySelector('#extension') as HTMLElement;
                elementDiv.style.cssText = 'display:none';
            }
        });
    }
}
</script>

<style scoped>
.com-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
}
.com-chart {
    width: 100%;
    height: 100%;
    overflow: hidden;
}
.title-search {
    line-height: 30px;
    height: 30px;
    margin-left: 20px;
}
.user-item {
    width: 200px;
    float: right;
    margin-right: 4px;
}
</style>
